import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class CameraPage extends StatelessWidget {
  final CameraDescription camera;

  const CameraPage({Key? key, required this.camera}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: CameraScreen(camera: camera),
    );
  }
}

class CameraScreen extends StatefulWidget {
  final CameraDescription camera;

  const CameraScreen({Key? key, required this.camera}) : super(key: key);

  @override
  _CameraScreenState createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;
  String? _imagePath;

  @override
  void initState() {
    super.initState();
    _controller = CameraController(
      widget.camera,
      ResolutionPreset.high,
    );

    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Camera Preview')),
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Column(
              children: [
                Expanded(
                  flex: 4,
                  child: CameraPreview(_controller),
                ),
                if (_imagePath != null)
                  Expanded(
                    flex: 3,
                    child: Image.file(File(_imagePath!)),
                  ),
              ],
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed: () async {
          try {
            await _initializeControllerFuture;

            // 拍摄照片并保存到临时路径
            final image = await _controller.takePicture();

            // 获取应用的文档目录
            final directory = await getApplicationDocumentsDirectory();

            // 创建保存照片的路径
            final imagePath = path.join(directory.path, '${DateTime.now()}.png');

            // 将照片从临时路径复制到新的路径
            final imageFile = File(image.path);
            final savedImage = await imageFile.copy(imagePath);

            // 更新UI以显示保存的照片
            setState(() {
              _imagePath = savedImage.path;
            });

            // 可选：显示保存成功的消息
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('照片已保存到 $imagePath')),
            );
          } catch (e) {
            print(e);
          }
        },
      ),
    );
  }
}